package org.ns.learn.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.ns.learn.rpc.codec.RpcMessageRequestDecode;
import org.ns.learn.rpc.codec.RpcMessageResponseEncode;
import org.springframework.context.ApplicationContext;

public class RpcServer {
    private ApplicationContext applicationContext;

    public RpcServer(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void start(int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup);
        sb.channel(NioServerSocketChannel.class);
        sb.option(ChannelOption.SO_BACKLOG, 10000);
        sb.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new RpcMessageRequestDecode());
                p.addLast(new RpcMessageResponseEncode());
                p.addLast(new RpcServerHandler(applicationContext));
            }
        });
        try {
            ChannelFuture channelFuture = sb.bind(port).sync();
            System.out.println("服务器启动: " + port);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
